package com.mio.web.controller.moive;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.controller.CrudController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mio.web.common.MioUtil;
import com.mio.web.common.ProcessInfo;
import com.mio.web.entity.moive.Movie;
import com.mio.web.entity.moive.MovieSch;
import com.mio.web.service.moive.MovieService;
import com.mio.web.util.FileUploadListener;

@Controller
public class MovieController extends CrudController<Movie, MovieService> {

	@RequestMapping("/getIndex.do")
	public ModelAndView getIndex(HttpServletRequest request) {
		ModelAndView model = new ModelAndView("/index.jsp");
		return model;
	}

	// ������¼
	@RequestMapping("/addMovie.do")
	public @ResponseBody MessageResult addMovie(HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		MessageResult result = null;
		try {
			String relPath = "/upload/movie/";
			String fileName = file.getOriginalFilename();
			File targetFile = MioUtil.getUploadFile(request, "movie", fileName,response);
			if (targetFile != null) {
				// 保存
				file.transferTo(targetFile);
				// 保存到moive表中
				Movie movie = new Movie();
				movie.setMovieName(fileName);
				movie.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				movie.setMovieUrl(relPath + fileName);
				result = this.save(movie);
				resultMap.put("success", true);
				resultMap.put("info", movie);

			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}

		if (resultMap.get("success").toString().equals("true")) {
			return result;
		} else {
			return error("上传视频失败！");
		}

	}

	// ɾ����¼
	@RequestMapping("/delMovie.do")
	public @ResponseBody MessageResult delMovie(Movie entity) {
		return this.delete(entity);
	}

	// �޸ļ�¼
	@RequestMapping("/updateMovie.do")
	public @ResponseBody MessageResult updateMovie(Movie entity,HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response) {
		Movie old = this.getService().get(entity.getId());
		int change0 = Integer.parseInt(request.getParameter("change0"));
		boolean flag = false;
		//表示修改
		if(change0>0){
			flag = true;
		}
		if(flag){
			try {
				String relPath = "/upload/movie/";
				String fileName = file.getOriginalFilename();
				File targetFile = MioUtil.getUploadFile(request, "movie", fileName,response);
				if (targetFile != null) {
					// 保存
					file.transferTo(targetFile);
					// 保存到moive表中
					entity.setMovieName(fileName);
					if(entity.getCreatedTime() == null){
						entity.setCreatedTime(old.getCreatedTime());
					}
					entity.setMovieUrl(relPath + fileName);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return this.update(entity);
	}

	// ������ѯ��ҳ����
	@RequestMapping("/listMovie.do")
	public @ResponseBody GridResult listMovie(MovieSch searchEntitySch) {
		return this.query(searchEntitySch);
	}

	// ������ѯ���������м�¼
	@RequestMapping("/listAllMovie.do")
	public @ResponseBody Object listAllMovie(MovieSch searchEntitySch) {
		return this.queryAll(searchEntitySch);
	}

	// ��ȡ��ϸ��Ϣ
	@RequestMapping("/getMovieById.do")
	public @ResponseBody Movie getMovieById(Movie entity) {
		return this.getService().get(entity.getId());
	}

	/**
	 * process 获取进度
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/processMovie.do")
	@ResponseBody
	public Object processMovie(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println(request.getSession().getAttribute("currentUploadStatus").toString());
		return (ProcessInfo) request.getSession().getAttribute("currentUploadStatus");
	}

	/**
	 * 获取首页的videoUrl
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getIndexMoive.do")
	public @ResponseBody Map<String, Object> getIndexMoive(HttpServletRequest request) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Movie movie = this.getService().getIndexMoive();
			resultMap.put("success", true);
			resultMap.put("info", movie);

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		return resultMap;
	}

	/**
	 *上传到指定目录测试方法
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/testUpload.do")
	public @ResponseBody Map<String, Object> testUpload(
			@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response)
					throws IOException {
		String fileName = "mio.txt";
		String filePath = request.getSession().getServletContext().getRealPath("exception");
		File dir = new File(filePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File exceptionFile = new File(dir, fileName);
		if (!exceptionFile.exists()) {
			exceptionFile.createNewFile();
		}
		FileWriter fileWriter = new FileWriter(exceptionFile, false); // true代表追加
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			File targetFile = MioUtil.getUploadFile(request, "movie", file.getOriginalFilename(),response);
			file.transferTo(targetFile);
			resultMap.put("success", true);
			resultMap.put("info", targetFile.getAbsolutePath());

		} catch (Exception e) {
			e.printStackTrace();
			fileWriter.write(e.getMessage());
			fileWriter.flush();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		fileWriter.close();
		return resultMap;
	}
	
	
	/**
	 * 进度条测试方法
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ProgressServlet.do")
	public @ResponseBody Object  testProgress(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//response.setContentType("text/html");
		//response.setHeader("Cache-Control", "no-cache");
		//PrintWriter out = response.getWriter();

		HttpSession session = request.getSession(true);
		if (session == null) {
			//out.println("Sorry, session is null"); // just to be safe
			return null;
		}

		return (ProcessInfo)(request.getSession().getAttribute("progress"));

	}

}
